package com.zz.framework.core.base

import android.app.Activity
import android.content.ClipData
import android.content.Context
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.zz.framework.core.event.AccountBannedEvent
import com.zz.framework.core.event.ClearActivityEvent
import com.zz.framework.core.event.TokenFiredEvent
import com.zz.framework.core.ext.clipboardManager
import com.zz.framework.core.ext.createPositiveDialog
import com.zz.framework.core.ext.showToast
import com.zz.framework.core.utils.IntentBuilder
import com.zz.framework.core.config.GlobalSetting
import com.zz.framework.R
import com.zz.framework.core.utils.ActivityStackManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

/**
 * Copyright © 2020 zanezhao All rights reserved.
 * Created on 2020/3/28 3:36 PM.
 * @version: V1.0
 */
open class BaseActivity : AppCompatActivity() {
    var currentActivity: BaseActivity? = null
    val tokenFireDialog by lazy {
        createPositiveDialog(
            R.string.text_token_fired,
            R.string.text_token_fired_relogin,
            android.R.string.ok,
            { dialog, which ->
                GlobalSetting.setToken("")
                IntentBuilder.Builder().setClass(this, GlobalSetting.getLoginActivityClass()).startActivity()
                EventBus.getDefault().post(ClearActivityEvent())
                dialog?.dismiss()
            },
            false,
            false
        )
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityStackManager.getInstance().onCreated(this)
    }

    override fun onResume() {
        super.onResume()
        setCurrActivity(this)
    }



    fun getClipContent(): CharSequence? {
        //检测剪切板内容
        if (clipboardManager?.hasPrimaryClip() == true && clipboardManager?.getPrimaryClip()?.getItemCount() ?: 0 > 0) {
            return clipboardManager?.getPrimaryClip()?.getItemAt(0)?.getText()
        }
        return null
    }

    fun clearClipboard() {
        clipboardManager?.let { manager ->
            try {
                val clipData = ClipData.newPlainText(null, "")
                manager.getPrimaryClip()?.let { manager.setPrimaryClip(it) }
                manager.setText(null)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        currentActivity = null
    }

    override fun onDestroy() {
        ActivityStackManager.getInstance().onDestroyed(this)
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun setCurrActivity(mActivity: BaseActivity) {
        this.currentActivity = mActivity
    }


    @Subscribe
    open fun onMessage(event: TokenFiredEvent) {
        if (event != null) {
            if (currentActivity == this && currentActivity!!.isDestroyed.not()) {
                runOnUiThread(Runnable {
                    tokenFireDialog.show()
                })
            }
        }
    }

    @Subscribe
    open fun onMessage(event: AccountBannedEvent) {
        if (event != null) {
            if (GlobalSetting.getLoginActivityClass() != this::class.java) {
                if (currentActivity == this && currentActivity!!.isDestroyed.not()) {
                    runOnUiThread(Runnable {
                        createPositiveDialog(
                            getString(R.string.text_tip),
                            event.message,
                            android.R.string.ok,
                            { dialog, which ->
                                GlobalSetting.setToken("")
                                IntentBuilder.Builder().setClass(this, GlobalSetting.getLoginActivityClass()).startActivity()
                                EventBus.getDefault().post(ClearActivityEvent())
                                dialog?.dismiss()
                            },
                            false,
                            false
                        ).show()
                    })
                }
            } else {
                showToast(event.message)
            }
        }
    }

    @Subscribe
    open fun onMessage(event: ClearActivityEvent) {
        if (GlobalSetting.getLoginActivityClass() != this::class.java) {
            finish()
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        return hideKeyboard(ev)
    }


    // 隐藏虚拟键盘
    open fun hideKeyboard(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideInput(v, ev) && v != null) {
                val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm?.hideSoftInputFromWindow(v!!.windowToken, 0)
            }
            return super.dispatchTouchEvent(ev)
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return if (window.superDispatchTouchEvent(ev)) {
            true
        } else super.dispatchTouchEvent(ev)
    }


    open fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (mViews.isNotEmpty()) {
            for (view in mViews) {
                return !isInView(view, event)
            }
        } else if (v != null && v is EditText) {
            // 点击的是输入框区域，保留点击EditText的事件
            return !isInView(v, event)
        }
        return false
    }

    /**
     * 点击的是否在view中
     * @param v
     * @param event
     * @return
     */
    open fun isInView(v: View?, event: MotionEvent): Boolean {
        if (v != null) {
            val leftTop = intArrayOf(0, 0)
            // 获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.height
            val right = left + v.width
            return event.x > left && event.x < right && event.y > top && event.y < bottom
        }
        return false
    }


//    open fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
//        if (v != null && v is EditText) {
//            val leftTop = intArrayOf(0, 0)
//            // 获取输入框当前的location位置
//            v.getLocationInWindow(leftTop)
//            val left = leftTop[0]
//            val top = leftTop[1]
//            val bottom = top + v.getHeight()
//            val right = left + v.getWidth()
//            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
//        }
//        return false
//    }

    var mViews = mutableListOf<View>()

    /**
     * 只需添加最外层ViewGroup 的 id
     */
    open fun setCannotHideInputViews(views: List<View>?) {
        this.mViews.clear()
        views?.forEach {
            this.mViews.add(it)
        }
    }


    protected fun startParentActivity(clazz: Class<out Fragment>) {
        IntentBuilder.Builder().startParentActivity(this, clazz)
    }

    protected fun startActivity(clazz: Class<out Activity>) {
        IntentBuilder.Builder().setClass(this, clazz).startActivity()
    }
}